package com.lucky.auth_boot.security.filter;

import com.alibaba.fastjson.JSON;
import com.lucky.auth_boot.common.Result;
import com.lucky.auth_boot.pojo.dto.UserDTO;
import com.lucky.auth_boot.pojo.po.UserPO;
import com.lucky.auth_boot.exception.BusinessException;
import com.lucky.auth_boot.utils.JwtUtil;
import com.lucky.auth_boot.utils.RedisUtil;
import com.lucky.auth_boot.utils.WebUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Resource
    RedisUtil redisUtil;
    public JwtAuthenticationFilter() {
    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从请求头或请求参数中获取JWT token

        String authorizationHeader = request.getHeader("Authorization");
        String token = null;
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            token = authorizationHeader.substring("Bearer ".length());
            // do something with the token
        }
        if (token == null || token.isEmpty()) {
            filterChain.doFilter(request, response);
            return;
        }

        try {
            UserPO userPO = JwtUtil.verifyAndGetUser(token);

//            判断token是否过期/其他地方登录
            assert userPO != null;
            UserDTO userDTO = JSON.parseObject(JSON.toJSONString(redisUtil.getValue("AuthorLogin:"+ userPO.getUid())), UserDTO.class);
            if (!userDTO.getToken().equals(token)) {
                throw new RuntimeException("用户令牌已失效");
            }

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    userDTO, null, userDTO.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } catch (Exception e) {
            // 验证失败，可以进行一些处理
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.error(e.getMessage());
        }
        filterChain.doFilter(request, response);
    }
}